﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace EasyMvvm.Tests
{
    [TestClass]
    public class MediatorTests
    {

        class TestMessage : MediatorMessage
        {

        }

        class MediatorTest
        {
            public bool HasRun;
            [MediatorMethod()]
            public void Test(TestMessage message)
            {
                HasRun = true;
            }
        }

        [TestMethod]
        public void RemoveTest()
        {
            MediatorTest test = new MediatorTest();
            Assert.IsFalse(Mediator.Instance.Unregister(test));
            Mediator.Instance.Register(test, true);
            Assert.IsTrue(Mediator.Instance.Unregister(test));
        }

        [TestMethod]
        public void TestSendMessage()
        {
            MediatorTest test = new MediatorTest();
            Mediator.Instance.Register(test, false);

            Assert.AreEqual<int>(Mediator.Instance.SendMessage(new TestMessage()), 1);
            Assert.IsTrue(test.HasRun);
            Mediator.Instance.Unregister(test);

            test.HasRun = false;

            Assert.AreEqual<int>(Mediator.Instance.SendMessage(new TestMessage()), 0);
            Assert.IsFalse(test.HasRun);
        }

        [TestMethod]
        public void TestWeakReferense()
        {
            MediatorTest test = new MediatorTest();
            Mediator.Instance.Register(test, false);
            test = null;
            GC.Collect();
            GC.WaitForFullGCComplete();
            GC.WaitForPendingFinalizers();
            Assert.AreEqual<int>(Mediator.Instance.SendMessage(new TestMessage()), 0);
        }

        [TestMethod]
        public void TestStrongReferense()
        {
            MediatorTest test = new MediatorTest();
            Mediator.Instance.Register(test, true);
            test = null;
            GC.Collect();
            GC.WaitForFullGCComplete();
            GC.WaitForPendingFinalizers();
            Assert.AreEqual<int>(Mediator.Instance.SendMessage(new TestMessage()), 1);
        }
    }
}
